/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "hilog/log.h"
#include "PagSurface.h"
#include "../common/common.h"

using namespace pag;
using namespace NativeXComponentSample;

void OHOS_PAGSuface::PAGSurfaceInit(OH_NativeXComponent *component, void *nativeWindow, void *eglContext)
{
    auto drawable = pag::GPUDrawable::FromWindow(component, nativeWindow, eglContext);
    std::shared_ptr<pag::GPUDrawable> pag_drawable = std::shared_ptr<pag::GPUDrawable>(drawable);
    std::shared_ptr<pag::PAGSurface> pag_surface = pag::PAGSurface::MakeFrom(pag_drawable);
    char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {'\0'};
    uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
    if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
        OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback",
                     "OnSurfaceCreatedCB: Unable to get XComponent id");
        return;
    }
    std::string idCompent = idStr;
    pagSurfaceMap_[idCompent] = pag_surface;
}
PAGSurface *OHOS_PAGSuface::GetPAGSurface(std::string &id)
{
    auto it = pagSurfaceMap_.begin();
    for (; it != pagSurfaceMap_.end(); it++) {
        OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN,
                     "INIT", "OHOS_PAGSuface pagSurfaceMap_[idCompent] %{public}p, %{public}s",
                     it->second.get(), it->first.c_str());
    }
    if (pagSurfaceMap_.find(id) == pagSurfaceMap_.end()) {
        return nullptr;
    } else {
        return pagSurfaceMap_[id] != nullptr ? pagSurfaceMap_[id].get() : nullptr;
    }
}
